/*
 * @lc app=leetcode.cn id=799 lang=typescript
 *
 * [799] 香槟塔
 */

// @lc code=start
function champagneTower(poured: number, query_row: number, query_glass: number): number {
  // 初始化第一层的容量
  let rowsCapacity: number[] = [poured];
  // 遍历到目标层
  for (let i = 1; i <= query_row; i++) {
    // 下一层的杯子数
    const nextRowCapacity = new Array(i + 1).fill(0);
    for (let j = 0; j < i; j++) {
      const val = rowsCapacity[j];
      // 杯子满了才会溢出到下一层
      if (val > 1) {
        nextRowCapacity[j] += (val - 1) / 2;
        nextRowCapacity[j + 1] += (val - 1) / 2;
      }
    }
    // 重置当前层
    rowsCapacity = nextRowCapacity;
  }

  return Math.min(1, rowsCapacity[query_glass]);
}
// @lc code=end
